import { setUUID } from "@/utils/uuid";
import { getCartListAPI, deleteCartAPI, getCheckCartAPI } from "@/api";

const state = {
	user_uuid: setUUID(),
	cartList: [],
};

const actions = {
	// get 购物车数据
	async getCartList({ commit }) {
		const res = await getCartListAPI();
		if (res.code === 200) {
			commit("GETCartList", res.data);
		}
	},

	// delete 购物车商品
	async deleteCart({ commit }, skuId) {
		const res = await deleteCartAPI(skuId);
		if (res.code === 200) {
			return "ok";
		} else {
			return Promise.reject(new Error("删除失败"));
		}
		// console.log("我好了");
	},

	// delete 选中的购物车商品
	deleteCheckedCart({ dispatch, state }) {
		const promiseAll = [];
		// 检查商品选中状态
		state.cartList.forEach((item) => {
			// 如果是选中状态，就将结果的promise实例，push到promiseAll中
			if (item.isChecked) {
				promiseAll.push(dispatch("deleteCart", item.skuId));
			}
		});
		return Promise.all(promiseAll);
	},

	// get 切换商品选中状态
	async getCartChecked({ commit }, { skuId, isChecked }) {
		const res = await getCheckCartAPI(skuId, isChecked);
		if (res.code === 200) {
			return "ok";
		} else {
			return Promise.reject(new Error("状态修改失败"));
		}
	},
	// get 修改全选状态
	getAllChecked({ dispatch, state }, isAllChecked) {
		const promiseAll = [];
		state.cartList.forEach((item) => {
			// 取出所有商品的id，选中状态为全选按钮的状态
			let promiseItem = dispatch("getCartChecked", {
				skuId: item.skuId,
				isChecked: isAllChecked,
			});
			promiseAll.push(promiseItem);
		});
		// console.log(promiseAll);
		return Promise.all(promiseAll);
	},
};

const mutations = {
	GETCartList(state, cartList) {
		if (cartList[0]) {
			state.cartList = cartList[0].cartInfoList;
		} else {
			state.cartList = [];
		}
	},
};
const getters = {};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
};
